package sspersonserver;

import sspersonserver.events.IConListener;
import sspersonserver.events.PacketEvent;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: Double
 * Date: 15.01.12
 * Time: 20:41
 * To change this template use File | Settings | File Templates.
 */
public class ConnectionServer implements Runnable
{
	private ServerSocket ss;
	private ArrayList<IConListener> iConListeners = new ArrayList<IConListener>();
	private static final ConnectionServer instance = new ConnectionServer();
	private ConnectionServer(){
		try {
			ss = new ServerSocket(2020);
		} catch (IOException e) {
			e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
		}


		/*Запуск логгера*/
		FileInputStream loggerConfig = null;
		try {
			loggerConfig = new FileInputStream("logger.properties");
			LogManager.getLogManager().readConfiguration(loggerConfig);
			FileHandler hand = new FileHandler("PersonServer.log");
			Logger log = Logger.getLogger("PersonServer");
			log.addHandler(hand);
		} catch (Error ex) {
			Logger.getLogger("PersonServer").log(Level.SEVERE, null, ex);
		}catch (Exception ex) {
			Logger.getLogger("PersonServer").log(Level.SEVERE, null, ex);
		} finally {
			try {
				loggerConfig.close();
			} catch (Exception ex) {
				Logger.getLogger("PersonServer").log(Level.SEVERE, null, ex);
			}
		}
	}
	public void addConListener(IConListener iCL)
	{
		iConListeners.add(iCL);
	}
	public void removeConListener(IConListener iCL)
	{
		iConListeners.remove(iCL);
	}


	public static ConnectionServer getInstance() {
		return instance;
	}
	
	private void fireConnect(Client c)
	{
		for(IConListener iCL:iConListeners)
		{
			iCL.onConnect(new PacketEvent(this,c));
		}

	}

	@Override
	public void run() {
		while(true){
			try {
				Socket s = ss.accept();
				Client c = new Client(s);
				fireConnect(c);

				/*if(Server.getClientProcessor() instanceof MultiClientProcessor)
				{
					Server.getClientProcessor().addClient(c);
				}else
				{
					new Thread(c).start();
				} */
				System.out.println("Client connected:"+s);
				Logger.getLogger("PersonServer").log(Level.SEVERE,"Client connected: "+s);
			} catch (IOException e) {
				e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
			}
		}
	}
}
